<template>
	<view class="detail-container">
		<view v-if="loading" class="loading-state">
			<u-loading-icon mode="circle" size="30"></u-loading-icon>
			<text>加载中...</text>
		</view>
		
		<template v-if="!loading && orderDetail"> 
			<!-- Basic Info -->
			<view class="info-section card">
				<view class="info-item">
					<view class="info-icon"><u-icon name="clock" size="20" color="#666666"></u-icon></view>
					<text class="info-label">日期</text>
					<text class="info-value">{{ orderDetail.businessDate | formatDate }}</text>
				</view>
				<view class="info-item">
					<view class="info-icon"><u-icon name="account" size="20" color="#666666"></u-icon></view>
					<text class="info-label">客户</text>
					<text class="info-value">{{ orderDetail.customerName || '无' }}</text>
				</view>
			</view>

			<!-- Goods List -->
			<view class="goods-section card">
				<view class="section-header">
					<text class="section-title">选中货品 ({{ orderDetail.salesDetailItemList ? orderDetail.salesDetailItemList.length : 0 }})</text>
					<text class="section-total">合计金额: ¥{{ orderDetail.totalAmount | formatAmount }}</text>
				</view>
				<view class="goods-list">
					<view class="goods-item" v-for="(item, index) in orderDetail.salesDetailItemList" :key="index">
						<view class="goods-image">
							<image :src="item.goodsImage || '/static/images/default-goods.png'" mode="aspectFill"></image>
						</view>
						<view class="goods-info">
							<view class="goods-name">{{ item.goodsName || '未知商品' }}</view>
							<view class="goods-detail">
								<text class="goods-count">数量：{{ item.quantity || 0 }}</text>
								<text class="goods-price">单价：¥ {{ item.unitPrice | formatAmount }}</text>
							</view>
							<view class="goods-amount">金额：¥ {{ item.totalPrice | formatAmount }}</view>
						</view>
					</view>
				</view>
			</view>

			<!-- Settlement Info -->
			<view class="settlement-section card">
				<view class="settlement-item">
					<text class="settlement-label">{{orderDetail.discountType==="amount"?"折扣金额":"折扣率"}}</text>
					<text class="settlement-value">{{ orderDetail.discount }}{{orderDetail.discountType==="amount"?"":"%"}}</text>
				</view>
                <view class="settlement-item">
					<text class="settlement-label">折后金额</text> <!-- Use discountedAmount -->
					<text class="settlement-value">¥ {{ orderDetail.discountedAmount | formatAmount }}</text>
				</view>
				<view class="settlement-item">
					<text class="settlement-label">本单实收</text> <!-- Use actualPayment -->
					<text class="settlement-value">¥ {{ orderDetail.actualPayment | formatAmount }}</text>
				</view>
				<view class="settlement-item">
					<text class="settlement-label">结算账户</text>
					<text class="settlement-value">{{ orderDetail.paymentMethod|| '未指定' }}</text>
				</view>
			</view>

			<!-- Remarks -->
			<view class="remark-section card">
				<view class="remark-header">
					<text class="remark-label">备注</text>
					<text class="remark-code">单号: {{ orderDetail.orderCode || '无' }}</text>
				</view>
				<view class="remark-content">
					{{ orderDetail.remark || '无备注' }}
				</view>
			</view>
		</template>

		<view v-if="!loading && !orderDetail" class="empty-state">
			<u-empty mode="data" text="无法加载订单详情"></u-empty>
		</view>

		<!-- Bottom Actions -->
		<view class="bottom-actions">
			<button class="action-btn delete" @click="confirmDeleteOrder">删除</button>
			<button class="action-btn edit" @click="editOrder">编辑</button>
		</view>

		<!-- Delete Confirmation Modal -->
		<u-modal :show="deleteModalVisible" content="确定要删除该销售单吗？此操作不可恢复。" :showCancelButton="true" @confirm="deleteOrder" @cancel="deleteModalVisible = false"></u-modal>
		
	</view>
</template>

<script>
import api from '@/utils/api.js';

export default {
	data() {
		return {
			orderId: null,
			orderDetail: null,
			loading: true,
			deleteModalVisible: false,
		}
	},
	filters: {
        formatDate(timestamp) {
            if (!timestamp) return '';
            // 假设 timestamp 是 Date 可以解析的格式 (如 ISO 字符串或数字)
            const date = new Date(timestamp);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            // 可选: 如果需要，添加时间
            // const hours = String(date.getHours()).padStart(2, '0');
            // const minutes = String(date.getMinutes()).padStart(2, '0');
            // return `${year}-${month}-${day} ${hours}:${minutes}`;
            return `${year}-${month}-${day}`;
        },
        formatAmount(value) {
            const num = Number(value);
            if (isNaN(num)) {
                return '0.00';
            }
            return num.toFixed(2);
        }
    },
	onLoad(options) {
		if (options.id) {
			this.orderId = options.id;
            uni.setNavigationBarTitle({ title: '销售单详情' }); 
		} else {
			console.error('缺少订单 ID');
			uni.showToast({ title: '无效的订单ID', icon: 'none' });
            this.loading = false;
			// 可选: 返回上一页
			// setTimeout(() => uni.navigateBack(), 1500);
		}
	},
    // 修改 onShow，始终加载数据（如果 orderId 存在）
    onShow() {
        console.log('页面 onShow 触发，加载/重新加载订单详情');
        if (this.orderId) {
            this.loadOrderDetail();
        } else {
            console.log('orderId无效，onShow跳过加载');
            // 如果orderId都没有，可能需要处理错误或返回
            if (!this.loading) { // 避免在已有错误处理时重复提示
               uni.showToast({ title: '缺少订单信息', icon: 'none' });
            }
        }
    },
	methods: {
		loadOrderDetail() {
			this.loading = true;
			console.log(`Fetching details for sales order ID: ${this.orderId}`);
			
            api.getSalesDetail(this.orderId) 
               .then(res => {
                   console.log("Sales Order Detail Response:", res);
                   const detailData = res.data || res; 
                   if (detailData && typeof detailData === 'object') { 
                       this.orderDetail = detailData;
                       console.log(222,this.orderDetail)
                       // --- Fetch Customer Name based on customerId ---
                       if (this.orderDetail.customerId) {
                           console.log(`Fetching customer details for ID: ${this.orderDetail.customerId}`);
                           api.getCustomer(this.orderDetail.customerId)
                              .then(customerRes => {
                                  console.log("Customer Detail Response:", customerRes);
                                  // ** Adjust data access based on getCustomer response **
                                  const customerData = customerRes.data || customerRes;
                                  if (customerData && customerData.customerName) {
                                      // Update the orderDetail object with the fetched name
                                      // Use $set to ensure reactivity if orderDetail wasn't initially defined with customerName
                                      this.$set(this.orderDetail, 'customerName', customerData.customerName);
                                      console.log(`Updated customer name to: ${customerData.name}`);
                                  } else {
                                       console.warn('Customer details fetched but name is missing or invalid format.');
                                       // Keep the original name if available, otherwise fallback
                                       if (!this.orderDetail.customerName) {
                                            this.$set(this.orderDetail, 'customerName', '客户信息加载失败');
                                       }
                                  }
                              })
                              .catch(customerErr => {
                                  console.error(`Failed to fetch customer details for ID ${this.orderDetail.customerId}:`, customerErr);
                                  // Keep the original name if available, otherwise show error indication
                                  if (!this.orderDetail.customerName) {
                                     this.$set(this.orderDetail, 'customerName', '客户信息加载失败');
                                  }
                              });
                       } else {
                            // If no customerId, ensure customerName exists or set default
                            if (!this.orderDetail.customerName) {
                                this.$set(this.orderDetail, 'customerName', '未指定客户'); 
                            }
                            console.log('No customerId found in order detail.');
                       }
                       // --- End Fetch Customer Name --- 

                       if (!this.orderDetail.itemList) {
                           this.orderDetail.itemList = [];
                       }

                   } else {
                       console.error("收到的订单详情数据格式无效");
                       uni.showToast({ title: '获取详情数据格式错误', icon: 'none' });
                       this.orderDetail = null; 
                   }
               })
               .catch(err => {
                   console.error("获取销售订单详情失败:", err);
                   uni.showToast({ title: '加载订单详情失败', icon: 'none' });
                   this.orderDetail = null; 
               })
               .finally(() => {
                   // 确保 loading 状态在所有异步操作后解除
                   this.loading = false; 
               });
		},
		editOrder() {
			console.log('Edit button clicked for order:', this.orderId);
            // Navigate to the new edit page
            uni.navigateTo({ 
                url: `/pages/sales/edit?id=${this.orderId}`,
                fail: (err) => {
                    console.error("Navigate to sales edit page failed:", err);
                    uni.showToast({ title: '无法打开编辑页面', icon: 'none' });
                }
            });
		},
		confirmDeleteOrder() {
			this.deleteModalVisible = true;
		},
		deleteOrder() {
            if (!this.orderId) return;
            uni.showLoading({ title: '删除中...' });
            console.log(`正在删除销售订单 ID: ${this.orderId}`);

            // --- 重要: 用实际的 API 调用替换 --- 
            // 假设 api.js 有一个类似 deleteSalesOrder(id) 的函数
            // API 调用结构示例:
            api.deleteSales(this.orderId) // 用您实际的函数名替换 deleteSalesOrder
               .then(res => {
                    uni.hideLoading();
                    // **根据您的 API 响应调整成功检查逻辑**
                    if (res.code === 200 || res.success) { 
                        uni.showToast({ title: '删除成功', icon: 'success' });
                        // 通知列表页刷新
                        uni.$emit('refreshDetailList', { type: 'outbound' }); // 如果需要，调整类型
                        setTimeout(() => {
                            uni.navigateBack();
                        }, 1500);
                    } else {
                        console.error("删除失败，API 响应:", res);
                        uni.showToast({ title: res.msg || '删除失败', icon: 'none' });
                    }
               })
               .catch(err => {
                   console.error("删除销售订单失败:", err);
                   uni.hideLoading();
                   uni.showToast({ title: '删除失败，请重试', icon: 'none' });
               });
            // --- 结束替换 API 调用 --- 

            /* // 用于测试的模拟删除
            setTimeout(() => {
                uni.hideLoading();
                uni.showToast({ title: '删除成功 (模拟)', icon: 'success' });
                uni.$emit('refreshDetailList', { type: 'outbound' });
                setTimeout(() => { uni.navigateBack(); }, 1500);
            }, 1000);
            */
        }
	}
}
</script>

<style lang="scss" scoped>
page {
	background-color: #f5f7fa;
}

.detail-container {
	padding: 20rpx;
	padding-bottom: 140rpx; /* 为固定的底部操作按钮留出空间 */
}

.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	color: #909399;
	font-size: 28rpx;
	text {
		margin-top: 10rpx;
	}
}

.card {
	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
}

/* Info Section */
.info-section {
	.info-item {
		display: flex;
		align-items: center;
		min-height: 70rpx;
		padding: 10rpx 0;
		&:not(:last-child) {
			border-bottom: 1rpx solid #f0f0f0;
		}
		.info-icon {
			margin-right: 15rpx;
		}
		.info-label {
			font-size: 28rpx;
			color: #333333;
			width: 140rpx;
		}
		.info-value {
			flex: 1;
			font-size: 28rpx;
			color: #666666;
			text-align: right;
		}
	}
}

/* Goods Section */
.goods-section {
	padding: 0; /* 移除卡片内边距以使头部/列表占满宽度 */
	.section-header {
		display: flex;
		justify-content: space-between;
		padding: 25rpx 30rpx;
		border-bottom: 1rpx solid #eeeeee;
		.section-title, .section-total {
			font-size: 28rpx;
			color: #333333;
		}
	}
	.goods-list {
		padding: 10rpx 30rpx 30rpx; /* Add padding around items */
		.goods-item {
			display: flex;
			padding: 20rpx 0;
			&:not(:last-child) {
				border-bottom: 1rpx solid #f0f0f0;
			}
			.goods-image {
				width: 100rpx;
				height: 100rpx;
				margin-right: 20rpx;
				flex-shrink: 0;
				image {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
					background-color: #f5f5f5;
				}
			}
			.goods-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				.goods-name {
					font-size: 28rpx;
					color: #333333;
					margin-bottom: 10rpx;
				}
				.goods-detail {
					display: flex;
					margin-bottom: 10rpx;
					.goods-count, .goods-price {
						font-size: 24rpx;
						color: #666666;
						margin-right: 30rpx;
					}
				}
				.goods-amount {
					font-size: 24rpx;
					color: #666666;
				}
			}
		}
	}
}

/* Settlement Section */
.settlement-section {
	.settlement-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		min-height: 70rpx;
		padding: 15rpx 0;
		&:not(:last-child) {
			border-bottom: 1rpx solid #f0f0f0;
		}
		.settlement-label {
			font-size: 28rpx;
			color: #333333;
		}
		.settlement-value {
			font-size: 28rpx;
			color: #666666;
		}
	}
}

/* Remark Section */
.remark-section {
	.remark-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15rpx;
		.remark-label {
			font-size: 28rpx;
			color: #333;
		}
		.remark-code {
			font-size: 24rpx;
			color: #999;
		}
	}
	.remark-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
		background-color: #f8f8f8;
		padding: 20rpx;
		border-radius: 8rpx;
		min-height: 100rpx;
	}
}

.empty-state {
	padding-top: 150rpx;
}

/* Bottom Actions */
.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	height: 100rpx;
	background-color: #fff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	padding: 10rpx 20rpx;
	box-sizing: border-box;
	z-index: 10;

	.action-btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30rpx;
		border-radius: 12rpx;
		margin: 0 10rpx;
		border: none;
		&::after {
			border: none;
		}

		&.delete {
			background-color: #fff1f0;
			color: #ff4d4f;
			border: 1rpx solid #ffa39e;
		}
		&.edit {
			background-color: #3ACBC1; // 使用您的主题色
			color: #fff;
		}
	}
}

</style> 